package com.tinem.platform.module.starter.web.filter;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className ChannelDatasourceFilter
 * @description TODO
 * @site
 * @company
 * @create 2021/12/7 20:00:46
 */
@Slf4j
@AllArgsConstructor
public class ChannelDatasourceFilter implements Filter {

    String active;

    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void destroy() {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String channel;
        if("dev".equalsIgnoreCase(active)){
            channel = ((HttpServletRequest)servletRequest).getHeader("channel");
        }else {
            channel = GatewayContext.getClient();
        }
        log.info("channel:{}",channel);
        try {
            DynamicDataSourceContextHolder.push(channel);
            filterChain.doFilter(servletRequest,servletResponse);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }
}
